//
//  SearchViewController.m
//  cherryproduct
//
//  Created by Enter zhao on 14-8-10.
//  Copyright (c) 2014年 cherry. All rights reserved.
//

#import "SearchViewController.h"
#import "ClassListViewController.h"

@interface SearchViewController ()

@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_serchBar becomeFirstResponder];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    searchView
    UIImageView* imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, IOS7_OR_LATER?26:6, 228+15, 30)];
    imageView.image = [UIImage imageNamed:@"searchRect"];
    
    imageView.userInteractionEnabled = YES;
    
    _serchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(1, 2, 228+15, 26)];
    _serchBar.delegate = self;
    _serchBar.keyboardType = UIKeyboardTypeWebSearch;
    _serchBar.placeholder=@"请输入搜索的商品名称";
    if (IOS7_OR_LATER) {
        _serchBar.searchBarStyle = UISearchBarStyleMinimal;

    }
    _serchBar.backgroundColor = [UIColor whiteColor];
//    [_serchBar setImage:[UIImage imageNamed:@"search"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    [_serchBar setImage:[UIImage imageNamed:@"clear"] forSearchBarIcon:UISearchBarIconClear state:UIControlStateNormal];
    [_serchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"searchRect"] forState:UIControlStateNormal];

    _serchBar.backgroundImage = [UIImage imageNamed:@"searchRect"];
    [imageView addSubview:_serchBar];
    [self.navigationBar addSubview:imageView];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    if ([defaults objectForKey:@"SearchHistory"]) {
        _searchArray = _possibleItems = [[NSMutableArray alloc] initWithArray:[defaults objectForKey:@"SearchHistory"] copyItems:YES];
    }
    else
    {
        _searchArray = _possibleItems = [[NSMutableArray alloc] init];
    }

    //    tableView
    _searchTableView = [[UITableView alloc] initWithFrame:CGRectMake(8, 0, 304, 0/*120*/)];
    _searchTableView.delegate = self;
    _searchTableView.dataSource = self;
    UIImageView* searchBackground = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 304, 120)];
    searchBackground.image = [UIImage imageNamed:@"searchBackground"];
    searchBackground.userInteractionEnabled = YES;
    [_searchTableView setBackgroundView:searchBackground];
    [self.myView addSubview:_searchTableView];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)clearHistoryAction:(UIButton*)sender
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:nil forKey:@"SearchHistory"];
    [defaults synchronize];
    if (_possibleItems.count) {
        [_possibleItems removeAllObjects];
    }
    if (_searchArray.count) {
        [_searchArray removeAllObjects];
    }
    [_searchTableView reloadData];
}
#pragma mark - searchbar
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF CONTAINS %@",_serchBar.text];
    NSLog(@"%@",[_possibleItems filteredArrayUsingPredicate:pred]);
    _searchArray = (NSMutableArray*)[_possibleItems filteredArrayUsingPredicate:pred];
    
    if ([searchBar.text isEqualToString:@""]) {
        _searchArray = _possibleItems;
    }
    [_searchTableView reloadData];
    

}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [UIView animateWithDuration:0.4f animations:^{
        _searchTableView.frame = CGRectMake(8, 0, 304, 120+50+30);
    }];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    BOOL b = NO;
    for (NSString* str in _possibleItems) {
        if ([str isEqualToString:_serchBar.text]) {
            b = YES;
        }
        
    }
    if (_possibleItems.count==0) {
        [_possibleItems addObject:_serchBar.text];
    }
    else
    {
        if (b) {
//            push
            ClassListViewController* vc = [[ClassListViewController alloc]init];
            vc.issearch = YES;
            NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:_serchBar.text,@"kwords", nil];
            [vc getuseparamclasslistdata:dic];
            [self.navigationController pushViewController:vc animated:YES];
            return;
        }
        else
        {
           [_possibleItems addObject:_serchBar.text];
        }
    }
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:_possibleItems forKey:@"SearchHistory"];
    [defaults synchronize];
    
    //            push
    ClassListViewController* vc = [[ClassListViewController alloc]init];
    vc.issearch = YES;
    NSDictionary* dic = [[NSDictionary alloc] initWithObjectsAndKeys:_serchBar.text,@"kwords", nil];
    [vc getuseparamclasslistdata:dic];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _searchArray.count;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell * cell = [[UITableViewCell alloc] init];
    cell.backgroundColor = [UIColor colorWithRed:249.0/255.0 green:249.0/255.0 blue:249.0/255.0 alpha:1.0];
    
    NSInteger p_index = [_searchArray count] - indexPath.row - 1;
    if (p_index < [_searchArray count] && p_index > -1) {
        NSString * str_title = [_searchArray objectAtIndex:p_index];
        if (str_title) {
            UILabel * label = [UILabel initWithCommonParameters:CGRectMake(20, 0, 300, 30)
                                                           text:str_title
                                                      textColor:[UIColor grayColor]
                                                       fontSize:14
                                                      isNewLine:NO];
            UIImageView * searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(275, 8, 11, 12)];
            searchImage.image = [UIImage imageNamed:@"search"];
            [cell addSubview:searchImage];
            [cell addSubview:label];
        }
    }
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ClassListViewController* vc = [[ClassListViewController alloc]init];
    vc.issearch = YES;
    
    NSInteger p_index = [_searchArray count] - indexPath.row - 1;
    NSString * str_keyword = @"";
    if (p_index < [_searchArray count] && p_index > -1) {
        str_keyword = [_searchArray objectAtIndex:p_index];
    }
    
    if (![_serchBar.text isEqualToString:@""]) {
        [vc getuseparamclasslistdata:[[NSDictionary alloc] initWithObjectsAndKeys:str_keyword, @"kwords", nil]];
    } else {
        [vc getuseparamclasslistdata:[[NSDictionary alloc] initWithObjectsAndKeys:str_keyword,@"kwords", nil]];
    }
    
    [self.navigationController pushViewController:vc animated:YES];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 30;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (!_possibleItems.count) {
        return nil;
    }
    UIButton* clearHistory = [[UIButton alloc] initWithCommonParametersAndTarget:CGRectMake(0, 0, 304, 30) backGroundImage:[UIImage imageNamed:@"searchBackground"] target:self action:@selector(clearHistoryAction:)];
    [clearHistory setTitle:@"清除搜索记录" forState:UIControlStateNormal];
    
    
    [clearHistory setTitleColor:[UIColor colorWithRed:43.0/255.0 green:124.0/255.0 blue:246.0/255.0 alpha:1.0] forState:UIControlStateNormal];

    return clearHistory;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
